package com.zhijian.warehouse.manage.service.impl;

import com.zhijian.util.BeanUtil;
import com.zhijian.warehouse.manage.service.CacheDao;
import com.zhijian.warehouse.manage.dao.DictionaryMapper;
import com.zhijian.warehouse.manage.entity.po.Dictionary;
import com.zhijian.warehouse.manage.service.DictionaryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 字典表业务处理层
 *
 * @DateTime 2021-02-27 14:19:18
 * @version: 1.0.1
 */
@Slf4j
@Service
public class DictionaryServiceImpl implements DictionaryService {

    @Autowired
    private DictionaryMapper mapper;

    @Autowired
    private CacheDao cacheDao;
    
    public static final String DICT_CACHE_KEY = "global:cache:dictionary:%s_%s";
    

    /**
     * {@inheritDoc}
     */
    @Override
    public List<Dictionary> selectByName(String name) {
        Map<String, List<Dictionary>> data = selectByNames(Collections.singletonList(name));
        return data.get(name);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Map<String, List<Dictionary>> selectByNames(List<String> names) {
        //TODO 不缓存，调用量少（后续有需求改动）
        List<Dictionary> dicts = mapper.selectByNames(names);
        return dicts.stream().collect(Collectors.groupingBy(Dictionary::getName));
    }
    
    private void cacheDict(String name, String code, String value) {
        cacheDao.support().set(String.format(DICT_CACHE_KEY, name, code), value, -1L, null);
    }
    
    /**
     * {@inheritDoc}
     */
    @Override
    public boolean restoreCache() {
        //存放字典表数据
        List<Map<String, Object>> list = mapper.selectPageData(new HashMap<String, Object>());
        String name = null;
        String code = null;
        String value = null;
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = list.get(i);
            name = BeanUtil.getStr4Map("name", map, null);
            code = BeanUtil.getStr4Map("code", map, null);
            value = BeanUtil.getStr4Map("value", map, null);
            cacheDict(name, code, value);
        }
        return true;
    }
}
